import axios from 'axios';
import { ElLoading } from 'element-plus';
import Message from '@/utils/Message';
import VueCookies from 'vue-cookies';
import { useLoginStore } from "@/stores/loginStore";

const contentTypeForm = 'application/x-www-form-urlencoded;charset=UTF-8';
const contentTypeJson = 'application/json';
const responseTypeJson = 'json';
export const ApiURL = "http://172.17.1.26:9090";
export const ImgURL = "http://cos.tuxiw.cn";

let loading = null;

const instance = axios.create({
    withCredentials: true,
    baseURL: `${ApiURL}/api`,
    timeout: 10000,
});

// 请求前拦截器
instance.interceptors.request.use(
    config => {
        if (config.showLoading) {
            loading = ElLoading.service({
                lock: true,
                text: '加载中...',
                background: 'rgba(0, 0, 0, 0.7)',
            });
        }
        return config;
    },
    error => {
        if (loading) {
            loading.close();
        }
        console.error('请求发送失败:', error);
        return Promise.reject(error);
    }
);

// 请求后拦截器
instance.interceptors.response.use(
    response => {
        if (loading) {
            loading.close();
        }
        const { data } = response;
        if (data.code === 200) {
            return data;
        } else if (data.code === 401 || data.code === 400 || data.code === 403 || data.code === 500) {
            Message.error(data.message);
            return Promise.reject(data);
        } else if (data.code === 901) {
            const loginStore = useLoginStore();
            loginStore.setLogin(true);
            return Promise.reject({ showError: false });
        } else {
            Message.error(data.info || '未知错误');
            return Promise.reject(data);
        }
    },
    error => {
        if (loading) {
            loading.close();
        }
        console.error('响应错误:', error);
        if (error.response) {
            Message.error(error.response.data.message || '响应错误');
        } else {
            Message.error('网络错误');
        }
        return Promise.reject(error);
    }
);

const request = (config) => {
    const { url, params, dataType, showLoading = false, responseType = responseTypeJson, showError = true } = config;
    let contentType = contentTypeForm;
    let requestBody;
    if (dataType === 'json') {
        contentType = contentTypeJson;
        requestBody = JSON.stringify(params);
    } else {
        requestBody = new FormData();
        for (let key in params) {
            requestBody.append(key, params[key] == undefined ? '' : params[key]);
        }
    }

    const token = VueCookies.get('token');
    const headers = {
        'Content-Type': contentType,
        'Authorization': token ? `Bearer ${token}` : '',
    };

    return instance.post(url, requestBody, {
        onUploadProgress: config.uploadProgressCallback,
        responseType,
        headers,
        showLoading,
        showError,
    }).catch(error => {
        if (showError) {
            Message.error(error.msg || '请求失败');
        }
        console.error('请求错误:', error);
        return null;
    });
};

export default request;